package com.yugao.fintech.draper.demos.mapstruct.convert;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.yugao.fintech.draper.demos.mapstruct.bo.ArtBO;
import com.yugao.fintech.draper.demos.mapstruct.domain.ArtDO;
import com.yugao.fintech.draper.demos.mapstruct.dto.ArtDTO;
import com.yugao.fintech.draper.demos.mapstruct.vo.ArtVO;
import org.mapstruct.*;
import org.mapstruct.factory.Mappers;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Mapper
public interface ArtConvert {

    /**
     * 获取ArtConvert的实现类
     */
    ArtConvert INSTANCE = Mappers.getMapper(ArtConvert.class);

    /**
     * DO---->DTO
     */
    @Mappings({@Mapping(source = "id", target = "userId"),
            @Mapping(source = "value", target = "value", qualifiedByName = "convertStringToList")})
    ArtDTO convert(ArtDO artDO);

    /**
     * DTO--->VO
     */
    @Mappings({@Mapping(target = "userId", ignore = true),
            @Mapping(source = "userId", target = "userName", qualifiedByName = "convertIdToName"),
            @Mapping(source = "value", target = "value", qualifiedByName = "convertListToString")})
    ArtVO convert(ArtDTO artDTO);

    /**
     * DO + VO ---> BO
     */
    @Mappings({@Mapping(source = "artDO.value", target = "a"), @Mapping(source = "artVO.userName", target = "b")})
    ArtBO convert(ArtDO artDO, ArtVO artVO);

    void updateVO(ArtDO artDO, @MappingTarget ArtVO artVO);

    @Named("convertStringToList")
    default List<String> convertStringToList(String val) {
        if (StrUtil.isBlank(val)) {
            return new ArrayList<>(0);
        }

        return Arrays.asList(val.split(","));
    }

    @Named("convertListToString")
    default String convertListToString(List<String> val) {
        if (CollectionUtil.isEmpty(val)) {
            return null;
        }

        return String.join(",", val);
    }

    @Named("convertIdToName")
    default String convertIdToName(Long id) {
        return "用户:" + id;
    }

}
